package service;

import bean.UrlGenerator;
import dao.UrlGeneratorDAO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Service;
import util.LRU;
import util.NumberTransfer;

/**
 * Created by YanYang on 2015/12/26.
 */
@Service("UrlGeneratorService")
public class UrlGeneratorService {
    @Autowired
    public UrlGeneratorService(UrlSaveService urlSaveService){
        this.urlSaveService = urlSaveService;
    }
    private UrlSaveService urlSaveService;

    ApplicationContext context = null;

    public long insertUrlAndGetId(String normalUrl){
        context = new ClassPathXmlApplicationContext("spring-mybatis.xml");
        UrlGeneratorDAO urlGeneratorDAO = (UrlGeneratorDAO)context.getBean("UrlGeneratorDAO");

        UrlGenerator urlGenerator = new UrlGenerator();
        urlGenerator.setNormalUrl(normalUrl);
        urlGeneratorDAO.insertUrlAndGetId(urlGenerator);
        long id = urlGenerator.getId();
        urlGenerator = null;
        return id;
    }

    public String tinyUrlSaveAndGetTinyUrl(String normalUrl){
        String tinyUrl = null;
        String tempUrl = LRU.lruLinkedHashMap.get(normalUrl);
        if(tempUrl != null && !tempUrl.equals("")){
            tinyUrl = tempUrl;
            return tinyUrl;
        }
        long urlID = insertUrlAndGetId(normalUrl);   //获得插入常规URL产生的ID号
        String _10to62 = NumberTransfer._10to62(urlID);  //将ID号转化为62进制字符串
        tinyUrl = "hongxiyang.me/" + _10to62; //生成tinyUrl
        LRU.lruLinkedHashMap.put(normalUrl,tinyUrl);
        /*
        保存urlID, normalUrl, tinyUrl到数据库
         */
        boolean succeed = urlSaveService.tinyUrlSave(urlID,normalUrl,tinyUrl);
        if(succeed) {
            return tinyUrl;
        }else{
            return "false";
        }

    }

    public String getNormalUrlByUrlID(long urlID_10){
        context = new ClassPathXmlApplicationContext("spring-mybatis.xml");

        UrlGeneratorDAO urlGeneratorDAO = (UrlGeneratorDAO)context.getBean("UrlGeneratorDAO");
        UrlGenerator urlGenerator = new UrlGenerator();
        urlGenerator.setId(urlID_10);
        urlGenerator = urlGeneratorDAO.getNormalUrlByID(urlGenerator);
        return urlGenerator.getNormalUrl();
    }
    /**
     * 测试用例
     * @param args
     */
    public static void main(String[] args){
        UrlSaveService urlSaveService = new UrlSaveService();
        UrlGeneratorService urlGeneratorService = new UrlGeneratorService(urlSaveService);
        String normalUrl = urlGeneratorService.getNormalUrlByUrlID(35);
        System.out.print(normalUrl);
    }
}
